﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InChatter.Client.Service
{
    public class MessageConfig
    {
        private static MessageConfig _Instance;
        public static MessageConfig Instance
        {
            set { _Instance = value; }
            get
            {
                if (_Instance == null)
                {
                    _Instance = ReadConfig();
                    if (_Instance == null)
                    {
                        _Instance = new MessageConfig();
                    }
                }
                return _Instance;
            }
        }
        private MessageConfig() { }

        public string SendMode { set; get; }

        public static void SaveConfig()
        {
            using (var db = NDatabase.OdbFactory.Open(ChatMsgCenter.Instance.DbUrl))
            {
                var result = db.QueryAndExecute<MessageConfig>().ToList();
                if (result.Count == 0)
                {
                    db.Store(MessageConfig.Instance);
                }
                else
                {
                    var instance = result.Last();
                    instance.SendMode = MessageConfig.Instance.SendMode;
                    db.Store(instance);
                }
            }
        }
        private static MessageConfig ReadConfig()
        {
            if (ChatMsgCenter.Instance.DbUrl == null) {
                return null;
            }
            using (var db = NDatabase.OdbFactory.Open(ChatMsgCenter.Instance.DbUrl))
            {
                var result = db.QueryAndExecute<MessageConfig>().ToList();
                if (result.Count == 0)
                {
                    return null;
                }
                return result.Last();
            }
        }
    }

}
